<?php
declare (strict_types = 1);

namespace app\admin\controller\user;

use app\admin\BaseController;
use app\admin\traits\UploadImage;
use app\common\model\user\User as UserModel;
use app\common\validate\User as UserValidate;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use app\common\model\user\Permission;

class User extends BaseController
{
    use UploadImage;

    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','update','delete','uploadAvatar','saveAssignment']],
    ];

    /**
     * 上传头像图片**
     */
    public function uploadAvatar(){
        return $this->upload(
            UserModel::UP_FIELD,
            UserModel::UP_FOLDER,
            ['width'=>320, 'height'=>320]
            );
    }

    /**
     * 显示资源列表
     */
    public function index()
    {
        return view('index',[
            'urlBase'   => config('filesystem.disks.public.url') . '/',
            'default_avatar' => config('app.default_avatar')
        ]);
    }

    /**
     * 资源列表
     */
    public function list()
    {
        try{
            //获取列表数据
            $data = UserModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['list']
        ]);
    }

    /**
     * 显示创建资源表单页.
     */
    public function create()
    {
        return view('create');
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        return $this->store($this->getModel(UserModel::class), '创建用户成功.', '创建用户失败.');
    }

    /**
     * 显示指定的资源
     */
    public function read(int $id)
    {
        return view('read',[
            'model' => $this->getModel(UserModel::class, $id)
        ]);
    }

    /**
     * 显示编辑资源表单页.
     */
    public function edit(int $id)
    {
        return view('edit',[
            'model' => $this->getModel(UserModel::class, $id)
        ]);
    }

    /**
     * 保存更新的资源
     */
    public function update(int $id)
    {
        return $this->store($this->getModel(UserModel::class,$id), '修改用户成功.', '修改用户失败.');
    }

    /**
     * 删除指定资源
     */
    public function delete(int $id)
    {
        //获取模型
        $model = $this->getModel(UserModel::class,$id,['topics']);
        try{
            if ($model->together(['topics'])->delete() === false){
                throw new Exception('删除用户失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'删除用户成功']);
    }

    /**
     * #指派角色页面
     * @return \think\response\View
     */
    public function assignment(int $id){
        return view('assignment',[
            'model' => $this->getModel(UserModel::class,$id),
            'allRoles' => Permission::getAllRoles(),
            'related' => Permission::getRelatedRoles(input('id/d'))
        ]);
    }

    /**
     * #保存指派数据
     */
    public function saveAssignment(int $id){
        try{
            //先获取角色模型
            $model = $this->getModel(UserModel::class, $id);

            $data = request()->only(['roles']);
            if ($data){
                validate(['roles'=>'array'])
                    ->check($data);
            }else{
                $data['roles'] = [];
            }

            if (!$model->saveRoles($data['roles']))
                throw new Exception('操作失败');

        }catch (ValidateException $e){
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }

    /**
     * 处理post提交
     * @param UserModel $model
     * @param string $okMsg
     * @param string $errMsg
     * @return \think\response\Json
     */
    private function store(UserModel $model, string $okMsg, string $errMsg){

        try{
            //验证数据
            $data = request()->only(['username','email','password','re_password','mobile','nickname','avatar']);
            if (empty($data['nickname'])) {
                unset($data['nickname']);
            }
            if (empty($data['mobile'])) {
                unset($data['mobile']);
            }

            if( !$model->isExists() ){
                if (empty($data['password'])) throw new ValidateException('密码不能为空');
            }
            validate(UserValidate::class)->check(array_merge($data, ['id'=>$model->id]));

            if (!empty($data['password'])){
                $data = array_merge($data, ['password_hash'=>UserModel::generatePasswordHash($data['password'])]);
            }
            //$data = array_merge($data, ['auth_key'=>UserModel::generateAuthKey()]);

            if( !$model->save($data) )
                throw new Exception($errMsg);


        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }

        //添加成功
        return json(['code'=>0,'msg'=>$okMsg]);
    }


}
